#include <QSize>
#include <QBrush>
#include "DataModel.h"
#include "RequestDescriptor.h"
#include "DataTable.h"
#include "ModTimeSlice.h"
#include "scImpl.h"

#define FCT "ModTimeSlice::ModTimeSlice"
ModTimeSlice::ModTimeSlice(PkType entityId, QObject * parent) :
	ModTable(entityId, parent)
{
	emit headerDataChanged(Qt::Vertical, 0, rowCount(QModelIndex())-1);
	connect(DataModel::get(), SIGNAL(deadlineChangedSig()), this, SLOT(loadMyDataSl()));
	loadMyDataSl();
}

#undef FCT
#define FCT "ModTimeSlice::~ModTimeSlice"
ModTimeSlice::~ModTimeSlice()
{
}

#undef FCT
#define FCT "ModTimeSlice::data(i)"
QVariant ModTimeSlice::data(const QModelIndex & index, int role) const
{
	// ctrc(Trc::LOOP,APP,FCT)<<"role "<<role<<endl;
	switch(role)
	{
	case Qt::DisplayRole:
		return QVariant(ModTable::data(index.column(), rowMap.at(index.row())));
	default:
		break;
	}
	return ModTable::data(index, role);
}

#undef FCT
#define FCT "ModTimeSlice::mapRowsSl"
void ModTimeSlice::mapRowsSl(unsigned long transactionId)
{
	// see remark at ModTable::mapRowsSl
	ctrc(Trc::LOOP,APP,FCT)<<"trans "<<transactionId<<endl;
	if(transactionId && transactionId!=transId)
	{
		ctrc(Trc::LOOP,APP,FCT)<<"skipped trans "<<transactionId<<" waiting for "<<transId<<endl;
		return;
	}
	if(transactionId)
		transId=0;
	beginRemoveRows(QModelIndex(), 0, rowMap.size()-1);
	rowMap.clear();
	endRemoveRows();
	TimeType deadl(DataModel::get()->getDeadlineUTC());
	// switch(dt.getDomain()) case DOMAIN_DATATL or DOMAIN_DATAVS:
	// base on identity key
	DOsCIkIdx & idx(dt.getPayload().dos.get<DataObject::IkTag>());
	int i(0);
	PkType lastIk(0);
	for(DOsCIkIdx::const_iterator it(idx.begin()); it!=idx.end(); ++it)
	{
		PkType newIk(it->getIk());
		if(lastIk!=newIk && it->getIks()<=deadl && it->getIks2()>deadl)
		{
			ctrc(Trc::LOOP,APP,FCT)<<"map row "<<i<<" to IK "<<newIk<<" PK "<<it->getPk()<<endl;
			rowMap.push_back(it->getPk());
			lastIk=newIk;
			++i;
		}
	}
	// TODO beauty - pre-calculate number of rows: according to Qt beginInsertRows must be called before inserting data
	beginInsertRows(QModelIndex(), 0, rowMap.size()-1);
	endInsertRows();
	if(rowMap.empty())
		ctrc(Trc::LOOP,APP,FCT)<<"map is empty"<<endl;
	emit dataChanged(index(0, 0), index(rowCount(QModelIndex()), columnCount(QModelIndex())));
}

#undef FCT
#define FCT "ModTimeSlice::loadMyDataSl"
void ModTimeSlice::loadMyDataSl()
{
	DataModel * dm(DataModel::get());
	rq=Request(dt.getPk(), dm->getDeadlineUTC(), true);
	transId=dm->requestData(new RequestDescriptor(rq));
	if(!transId)
		ModTimeSlice::mapRowsSl(0);
}

#undef FCT
#define FCT "ModTimeSlice::setTouched"
void ModTimeSlice::setTouched()
{
	ctrc(Trc::LOOP,APP,FCT)<<"touching "<<rq<<endl;
	ModTable::setTouched();
	dt.getPayload().setTouched(rq);
}
